Building a Tip of the Day Application (Part 3): Submitting Tips to the Web Service
Jen deHaan
www.flash-mx.com
www.ejepo.com
www.deseloper.com
Want to keep your Tip of the Day content fresh? Let users submit the tips themselves. Contributors get to see their names in lights and be king (or queen) for a day if their tips gain the coveted "Tips of the Day" distinction.
If you've been following along with this series, you've already used screens to complete the application framework (part one) and connected it to the tip web service (part two). In this final section, you're going to develop the means for users to submit new tips.
Since you've come so far, it's only fair to give you a running version of the application itself. Here it is.
Go ahead; feel free to submit a tip. But don't get too distracted and forget to complete the third and final part of the project: hooking up the application code so users can submit tips.
Requirements
To complete this tutorial, you will need to install the following software and files:
Macromedia Flash MX Professional 2004
Download sample files for this tutorial
firstflash.zip (810KB)
Complete parts one and two of this article series:
- Building a Tip of the Day Application (Part 1): Using Screens and Components
- Building a Tip of the Day Application (Part 2): Working with Web Services
Binding Data to the Submit a Tip Interface
Adding the "submit a tip" feature is actually fairly simple
because it only takes five parameters (AuthorName_txt, AuthorEmail_txt,
AuthorURL_txt, TipTitle_txt and TipText_txt) and sends them to
the web service. Since this web service does not return any variables,
it is easy to set up because it only needs a handful of bindings and
one behavior.
Create the web service for submitting tips as follows:
- With the presentation screen selected, open the Web Services
panel (Ctrl+Shift+F10) and expand the
tipServiceweb service. - Right-click the
submitTipmethod. Select Add Method Call from the contextual menu. This adds a new instance of the WebServiceConnector component to the Stage. - Drag the new WebServiceConnector instance off the Stage with the
other data components and assign it an instance name of
submitTip_wsc.
Bind the parameters of the tip submission web service to interface items (components) on the submit screen:
-
In the Bindings tab of the Component Inspector panel, add five bindings (one for each of the parameters). To do this, click the Add Binding button (+) in the Component Inspector panel’s Bindings tab. In the Add Binding window, select each parameter and click OK to add the binding. When you’re done, the Bindings tab should look as it does below in Figure 1.
Figure 1. Data bindings in the Component Inspector panel
- Select the
params.AuthorNamebinding. Double-click the Value column next to bound to in the Name/Value section below the binding listings. The Bound To dialog box opens. - In the lower screen, double-click the value box to the right
of bound to. In the Bound To dialog box, navigate to the submit screen
and choose
TextInput, <AuthorName_txt>. This sets the Component path, addingtext : Stringto the Schema location pane. (See Figure 2.) - Press OK to bind the
params.AuthorNamedata object to its corresponding component in the submit screen. -
Repeat the process for
AuthorEmail,AuthorURL,TipTitleandTipText, changing the component path accordingly.

Figure 2. Binding params.AuthorName to the AuthorName_txt TextInput component instance on the submit screen.
Now, activate the submit button so it triggers the web service and redirects the user to the submitthankyou screen:
- Click the submit screen and select the Submit button on the Stage.
- In the Behaviors panel, click the Add Behavior button (+), then select
Data > Trigger Data Source from the contextual menu. Select the
submitTip_wsccomponent and click OK.
Test the application (Control-Enter). As you test, do the following:
- Enter a tip and press the Submit button. The web service sends an e-mail to the administrator with the data entered into the text fields.
- Press the "back" button on the thank you page. Notice that the values entered by the visitor remain in the text fields.
The final point can be annoying to users who want to add another tip; they probably don't want to have to delete the old tip values manually. When users click the back button, you will want to clear the existing form values for TipTitle_txt and TipText_txt. You can leave the person’s name, e-mail, and URL in the form fields because the user may reuse those values.
Here's a method for doing this as part of the on (click) script
for the Back button. You could also clear the form variables using an on
(reveal) on the submitthankyou screen directly if you
prefer. Each way of accomplishing this task has advantages and disadvantages.
Select the Back button on the submitthankyou screen. Add the
following code to the top of Actions panel, after the on (click)
{ as follows:
this._parent._parent.submit.TipTitle_txt.text = ""; this._parent._parent.submit.TipText_txt.text = "";
You can find these paths by using the Insert a target path button in
the Actions panel and clicking the instance you want. Now after someone
submits a tip and hits the Back button, the application clears out the
values for TipTitle_txt and TipText_txt.
Formatting Dates
Before assembling the rest of the DateChooser (calendar) component pieces, you need to add a function to convert dates from a Flash date format (zero-based) to a ColdFusion date format. (A ColdFusion component (CFC) provides the web service at http://www.flash-mx.com/ws/tipoftheday/tip.cfc?wsdl.)
Assign a date to this.dataHolder_dh.tipdate_str as follows:
- Click the presentation screen to select it.
-
Open the Actions panel and add the following function within the
onClipEvent (load)function:function dateFormat(dDate:Date):String { var nYear = dDate.getFullYear(); var nMonth = dDate.getMonth()+1; var nDay = dDate.getDate(); if (nMonth<10) { nMonth = "0"+nMonth; } if (nDay<10) { nDay = "0"+nDay; } return new String(nMonth+"/"+nDay+"/"+nYear); }This little function takes a single parameter, a date, and extracts the years, months, and days. It gives them leading zeros if the months or days are less than ten, and returns a new string back to the caller. Also, note that you are adjusting the month and adding 1 to the specified month to make the dates compatible with ColdFusion.
-
Modify the original code in the
onClipEvent (load)method to use the new dateFormat function to set a default date in the DataHolder instance. Change the code from:this.dataHolder_dh.tipdate_str = "09/04/2003";
to
this.dataHolder_dh.tipdate_str = dateFormat( new Date() );This sets a default date in the DataHolder component to the current date rather than to the hard-coded "09/04/2003" date.
- Test the application.
When you have changed the code, test the SWF to make sure everything works. Now the most recent tip is displayed instead of the tip from the hard-coded date.
Building the Calendar Browse Interface
Integrating the DateChooser (calendar) component is a fairly simple
proposition after you've built the dateFormat function.
When a user clicks a calendar date, the DateChooser code throws a change
event, which you can easily trap.
When a user clicks a date, you want to send her to the tip screen and show her the tip for the day she chose.
- On the search screen, select the DateChooser instance and open the Behaviors panel.
- Click the Add Behavior button and select Screen > Go to Slide from the contextual menu.
- In the Select Screen dialog box, select the tip screen and click the OK button.
- In the Behaviors panel, change the event from
scrollto change. Now when a user clicks a date, the screen will change.
Next, you need to set the value of the tipdate_str in the
DataHolder to the value of the currently selected date. Here's why: To
get the getTipByDate function to work in the web service,
you need to pass it a date. The date parameter that’s sent to the web
service is bound to the dataHolder_dh.tipdate_str parameter.
Therefore, before sending the user back to the tip page, you have to
update this date string in the DataHolder component to the date that
the user clicked on the calendar. Also, when the user clicks a date,
the date is passed as an ActionScript date object that you need to convert
to MM/DD/YYYY format before you can send it to the web service.
-
Select the DataChooser instance on the search screen. Open the Actions panel and add the following line of code above the // GoTo Screen comment.
this._parent._parent._parent.dataHolder_dh.tipdate_str = this._parent._parent._parent.dateFormat(this.selectedDate);
This code sets the value of
tipdate_strin thedataHolder_dhinstance to the value of the currently selected date and formats the date using the custom formatting function. Note that since you defined the function on the presentation screen, you have to use dot syntax to reference the function just as you would for a component instance. -
Enter the following code above the code you added in step 1.
if (this.selectedDate == undefined) { return; }The code checks if the current
selectedDateis undefined. If no date is defined, the rest of the code (including setting the value of thetipdate_strproperty in the DataHolder and the Go to Slide behavior) is skipped.Why do you need to do this? When working with the DateChooser component, if a user clicks a date to select it, then clicks the same date again, it becomes deselected. This leaves the value of
selectedDateundefined. However, the Tip of the Day code would still trigger the change event.To work around this, you're using the code in Step 2 to check the value of
selectedDateto see if it is defined or not. If the value hasn’t been defined, then the user has most likely selected the same date twice and therefore you can disregard theclickevent.
Searching for Tips
Building the searchform and searchresult systems are
perhaps the most complex portions of the application. Sending the search
to the server is a simple process: You'll simply bind the keyword_txt TextInput
field to a WebServiceConnector component and use a behavior to trigger
the web service when a user clicks the Search button. Then you'll process
the returned XML results.
Calling the Search
Now you will add the code to call the search from the SWF file. Bind the search keyword text entry field to its corresponding parameter in the web service as follows:
- Select the presentation screen and open the Web Services
panel (Control+Shift+F10). Expand the
tipService, right-clickgetTipsByKeyword, add a method call, and close the Web Services panel. - Move the new WebServiceConnector component off the Stage with the
other data components and assign it an instance name of
getTipsByKeyword_wsc. - Open the Bindings tab in the Component Inspector panel and click the Add Binding button to open the Add Binding dialog box.
- Select the
Keyword : stringfrom the params object and click OK. -
Bind
params.Keywordto thekeyword_txtTextInput instance on the searchform screen. In the Bindings tab, select params.Keyword, and then double-click the field to the right of bound to. The Bound To dialog box opens. Find thekeyword_txtinstance in the tree and select it. (See Figure 3.) Click OK to close the Bound To dialog box.
Figure 3. Binding params.keyword to keyword_txt.
Add the Trigger Data Source behavior to the searchform screen as follows:
- On the searchform screen, select the Search button. Open
the Behaviors panel, click the Add Behavior button and select Data > Trigger
Data Source from the contextual menu. In the Select Data Source component
pane of the Trigger Data Source dialog box, select the
getTipsByKeyword_wscinstance and click OK. -
Make sure the Trigger Data Source behavior is above the Go to Slide behavior for the Search button on the searchform screen.
Because this Search button already has a behavior placed on it, confirm that the Trigger Data Source behavior appears before the Go to Slide behavior in the list in the Behaviors panel. To reorder behaviors, you can select the behavior you want in the Behaviors panel and click the Move Up or Move Down button in the upper right corner of the panel.
Figure 4. Behaviors for the Search button on the searchform screen
Receiving XML Results from a Web Service
If you are receiving XML from a web service, it is easy to consume the data by converting the packet into a Flash XML object. Just save the results as an XML packet in the DataHolder component, and then bind data to the XML packet.
Also, before you can bind the data from the XML packet, you have to import an XML schema so Flash can build the structure of the XML document. In this section, you will save and import a sample schema from XML generated by a trace statement that you pull from the Output panel.
- Select the presentation screen and click the DataHolder instance. Open the Component Inspector panel and click the Schema tab.
- Click the Add a Component Property (+) button in the upper left corner and, in the lower pane, set the field name for the new field to keywordresults. Set the field’s data type to XML.
-
Select the
getTipsByKeyword_wscinstance, and open the Actions panel. Enter the following ActionScript to trace results.on (result) { trace(this.results); } - Test your movie. When you do a keyword search, Macromedia Flash displays the XML packet sent back from the server to the Output window. Make sure you have multiple results and not a single result. (You can try searching for a blank string to return the maximum number of records.)
- Copy the XML packet from the Output window and save it to an XML file on your hard drive.
- Import the schema from the XML file you just saved as follows:
- Select the DataHolder instance on the presentation screen.
- With the
keywordresultsproperty selected in the upper Schema pane of the Component Inspector panel, click the Import a Schema from a Sample XML File button (located near the upper right corner of the Component Inspector panel, just below the Schema tab). This launches a file browser where you can locate the XML file you just saved on your hard drive. - Choose the XML file you saved and click Open. Now you can expand
the schema for the
keywordresultsproperty and see its structure.
- Remove the white space from the XML and set the value of
keywordresultsto the XML packet using ActionScript as follows:- Click the
getTipsByKeyword_wscinstance on the Stage. -
Open the Actions panel and replace the existing code with the code below:
on (result) { XML.prototype.ignoreWhite = true; this._parent.dataHolder_dh.keywordresults = new XML(this.results); }
- Click the
-
The first line of code tells Macromedia Flash to ignore white space in XML documents. (When working with XML, Flash can be sensitive to excessive white space; this command tells Flash to ignore all nodes that contain only white space and no data.) The second line of code sets the value of the keywordresults property in the DataHolder instance to the results of the XML packet. Because you’re using the XML() constructor, Flash converts the packet into a Flash XML object, which you can bind and manipulate in Flash.
-
Select the
dataHolder_dhinstance on the presentation screen and open the Bindings tab of the Component Inspector panel. Add a new binding forkeywordresults > results > tip. Set the direction of the binding to out. -
Double-click the bound to field in the lower pane of the Bindings tab to open the Bound To dialog box. In the Component Path pane, select the
results_lsList component and then selectdataProvideras the Schema location.By setting a List component’s
dataProviderproperty, you are able to set all of the list’s items at once. This means that once you've bound the List component to the tip array, the List contains each tip passed back from the web service.If you test the SWF file now, search, and receive multiple results, you will see that all of the fields from the XML document are merged into the label property for each record. To rearrange the fields before they are bound to the List component then, use a formatter. You can find a formatter in the Bindings tab of the Component Inspector panel.
Figure 6. Formatter for the keywordresults.results.tip data object.
-
Set the formatter to Rearrange Fields as shown in Figure 6. This rearranges the fields from the XML object before it is bound to the List component. For this example, set the Fields definition value to the following:
data=TipDateTime;label=TipTitle
You are binding the data property of the List component to the
TipDateTimefield from the web service’s returned XML. Likewise, you are setting the label for the List component to theTipTitlefrom the DataHolder component.
Figure 5. New dataHolder_dh binding to keywordresults.results.tip
Displaying a Tip from the Search Results
When a user gets a list of results from the keyword search, you want him to be able to view the result by clicking the tip’s name.
-
Write code to load a tip when a user clicks a search result.
- Select the
results_lsList component instance on the searchresult screen. - Open the Actions panel and add the following code onto the
results_lsinstance:this._parent._parent._parent.dataHolder_dh.tipdate_str = this.selectedItem.data;
Note: The data field of the List component holds preformatted date information from the web service. You can bind the data directly to the DataHolder component instead of having to call the custom
dateFormat()function in Macromedia Flash to format the date for you. - Select the
-
Add a behavior to load the tip screen when a user selects a tip from the List instance.
- Select the
results_lsinstance on the Stage. - Click the Add Behavior button in the Behaviors panel and select Screens > Go to Slide from the contextual menu.
- Select the tip screen and click OK to close the dialog box.
- Make sure the Go to Slide event is set to change in the pop-up menu.
- Check that the code you added to set the
tipdate_strvariable in theDataHolder_dhinstance comes before the code that loads a new screen but after theon change()handler, like this:on (change) this._parent._parent._parent.dataHolder_dh.tipdate_str = this.selectedItem.data; // GoTo Screen behavior
- Select the
-
Select Control > Test Movie to test the SWF file.
Now you can perform a keyword search, click a result in the List component instance, and be redirected to the home page with the new tip loading in.
-
Add code to check the number of values being returned by the XML packet and display a logical error informing the user that no results were found.
- Click the presentation screen and click the
getTipsByKeyword_wscinstance. -
Replace the existing code on the instance with the code below:
on (result) { var dh = this._parent.dataHolder_dh; XML.prototype.ignoreWhite = true; dh.keywordresults = new XML(this.results); if (dh.keywordresults.firstChild.childNodes.length == 0) { dh.keywordresults = new XML("<results><tip><TipTitle>No search results found.</TipTitle><TipDateTime /><ProductIcon /></tip></results>"); } }
The above code first creates a shortcut variable
(dh)to thedataHolder_dhinstance. This simplifies your subsequent code; you don't have to type out the full path to the component each time. Next, the if statement checks to see if the web service passes back any results. It does this by checking the length of thechildNodesarray, a Flash XML object Flash creates from the XML data returned by the web service. If the number of results equals zero, you create your own XML packet which will be bound to the List component. It will say No search results found rather than displaying an empty List with no results. This way, the user knows that the search successfully completed, but they just didn’t get any matching results. - Click the presentation screen and click the
-
Disable the List component if no search results were returned.
Although it seems like everything is possibly working, there is still one strange quirk in the application. If no search results are returned, the app displays an error message, but a user can still click on the No results were found message and generate an error when Flash tries to connect to the web service. This happens because the data field for the error message didn’t contain a date.
There are three possible solutions to this problem:
- Make up a date to pass in the error message. (This is not a very good solution because the date wouldn’t be meaningful at all.)
- Check that the date is valid before continuing with the
on (change)for the List component. -
Disable the List component if no results were found to prevent the user from clicking anything.
Both 2 and 3 are acceptable solutions, but because option 3 makes for a more interesting article and neither of the options are more than a couple lines of code, you’re stuck reading about the last option!
If you want to disable a List component (gray it out) or toggle whether a List component is selectable, modify the code on the
getTipsByKeyword_wsc.- Select
getTipsByKeyword_wscon the Stage. -
Open the Actions panel and change the
ifstatement to the following snippet:if (dh.keywordresults.firstChild.childNodes.length == 0) { dh.keywordresults = new XML("<results><tip><TipTitle>No search results found.</TipTitle><TipDateTime /><ProductIcon /></tip></results>"); this._parent.searchform.searchresult.results_ls.selectable = false; } else { this._parent.searchform.searchresult.results_ls.selectable = true; }
You’ve set the List component’s ability to be selectable based on the condition in the
ifstatement. You've added anelsecondition as well. This prevents a user from being able to select the error message.
Figure 7.
results_lsList component instance with enabled set to false
Note: Even though users cannot select the error message,
they can still mouse over it. The error message will highlight, however,
it won’t react to mouse clicks. If you find this behavior confusing,
you can replace selectable with enabled.
This makes the List component gray out.
Adding a Style Sheet
Although the Tip of the Day application is rather attractive already,
you can beautify it further by adding a Cascading Style Sheet (CSS) for
the tip text. With a style sheet, you can easily add colors for the active
links on the page or highlight the TipTitle. To add a Cascading
Style Sheet, insert the following code onto the presentation screen,
inside the onClipEvent (load) handler before the final bracket
(}):
var flash_css = new TextField.StyleSheet();
flash_css.setStyle(".text", {fontFamily:'Arial,Helvetica,sans-serif', fontSize:'11px', color:'#000000'});
flash_css.setStyle(".title", {fontFamily:'Arial,Helvetica,sans-serif', fontSize:'16px', color:'#999999', fontWeight:'bold'});
flash_css.setStyle("a", {fontFamily:'Arial,Helvetica,sans-serif', fontSize:'11px', color:'#0000FF'});
flash_css.setStyle("a:hover", {fontFamily:'Arial,Helvetica,sans-serif', fontSize:'11px', color:'#336699'});
this.tip.tip_txt.styleSheet = flash_css;
If you test your SWF file now, you see that the tip text field applies
colors to links on the current tip. To apply additional styles, modify
your code slightly and tell it to use these specific style names. Modify
the code on the getTipByDate_wsc component to something
similar to the following:
on (result) {
var tipObj:Object = this.results;
var tipStr:String = "";
tipStr += "<span class='title'>"+tipObj.TipTitle+"</span><br>";
tipStr += "<i>"+tipObj.TipDateTime+"</i><br>";>
tipStr += "<span class='text'>"+tipObj.TipText+"</span><br>";
if (tipObj.AuthorName.length>0) {
tipStr += tipObj.AuthorName+"<br>";
}
if (tipObj.AuthorEmail.length>0) {
tipStr += "<a href='mailto:"+tipObj.AuthorEmail+"' target='_blank'>"
+tipObj.AuthorEmail+"</a><br>";
}
if (tipObj.AuthorURL.length>0) {
tipStr += "<a href='"+tipObj.AuthorURL+"' target='_blank'>"+tipObj.AuthorURL+"</a><br>";
}
this._parent.tip.tip_txt.text = tipStr;
}
There you have it! You’re finished, and you now know more than you ever wanted to know about building a Tip of the Day web service-based application in Flash MX Professional. You can find the finished file with the source files you downloaded for this tutorial; it’s called tip.fla. If you have any questions on this tutorial, visit the Tip of the Day forum in the forums at www.flashmx2004.com.
About the author
Jen deHaan, who likes to talk about herself in the third person, is a Calgary based Flash ‘deseloper ‘ (designer/developer) who writes books and makes things with Flash. Jen has been involved in 15 books (usually) on Macromedia products since 2002. One of her recent books includes authoring Macromedia Flash MX 2004: Training from the Source for Macromedia Press. Jen started out as an eccentric and slightly paranoid art student, and has amazingly fooled people into thinking she knows ActionScript. This is despite what her friends might have said about her inability to pick up anything more complex than a paintbrush.Jen is the friendly web person championing many unsuccessful sites including www.flash-mx.com and www.flash2004.com. Her personal portfolio and rants can be found at www.ejepo.com, Flash help at www.flashmx2004.com, and she has dreams of managing a 7-11 to obtain free slurpees. Surprisingly few people can spell “deHaan”.